<?php
/**
 * Created by PhpStorm.
 * User: chniccs
 * Date: 2019-08-28
 * Time: 16:46
 */

namespace app\admin\controller;


use app\helper\CommonHelper;
use app\helper\TenantHelper;
use app\model\AdminTenant;
use app\util\ReturnCode;

class Site extends Base
{

    public function index()
    {

    }
    public function uploadCert(){
        $path = '/runtime/cert/wxpay/'.$this->getUserTid().'/' . date('Ymd', time()) . '/';
        $result = CommonHelper::upload($path,true);
        if($result['done']){
            return $this->buildSuccess($result);
        }else{
            return $this->buildFailed(ReturnCode::UPDATE_FAILED,'上传失败');
        }
    }

    /**
     * 获取操作站点列表
     * @return array
     * @throws \think\exception\DbException
     * @author zhaoxiang <zhaoxiang051405@gmail.com>
     */
    public function getSitesByAdmin()
    {

        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');

        $obj = new AdminTenant();
        if ($keywords) {
            $obj = $obj->whereLike('name', "%{$keywords}%");
        }
        $listObj = $obj->order('create_time DESC')->field('id,uid,name,create_time,expiration_time,level,status')->paginate($limit, false, ['page' => $start])->toArray();

        return $this->buildSuccess([
            'list' => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    /**
     * 管理员根据Tid获取信息
     * @return array
     */
    public function getByAdmin()
    {
        $tid = $this->request->param('id');
        if(!isset($tid)){
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $data = AdminTenant::get($tid)->getData();
        return $this->buildSuccess($data, '操作成功');
    }

    public function get()
    {
        $data = AdminTenant::get($this->getUserTid())->getData();
        return $this->buildSuccess($data, '操作成功');
    }

    public function save()
    {
        $postData = $this->request->post();
        unset($postData['expiration_time']);
        $result = AdminTenant::doSave($this->getUserTid(), $postData);
        if ($result) {
            return $this->buildSuccess(null, '操作成功');
        } else {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '更新失败');
        }
    }

    public function adminSave()
    {
        if (isset($postData['id'])) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $postData = $this->request->post();
        $result = AdminTenant::doSave($postData['id'], $postData,true);
        if ($result) {
            return $this->buildSuccess(null, '操作成功');
        } else {
            return $this->buildFailed(ReturnCode::UPDATE_FAILED, '更新失败');
        }
    }
}